package com.xin.handler;

import com.xin.constants.CommonResult;
import com.xin.exception.MyException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@ControllerAdvice
@RestController
public class HandlerBootException {

    @ExceptionHandler(value = Exception.class)
    public CommonResult<?> handlerException(Exception e){
        e.printStackTrace();
        CommonResult commonResult = new CommonResult();
        commonResult.setCode(500);
        commonResult.setMsg("内部服务器未知异常");
        return commonResult;
    }

    @ExceptionHandler(value = MyException.class)
    public CommonResult<?> handlerExceptionMyException(MyException myException){

        CommonResult commonResult =new CommonResult();
        String msg = myException.getMsg();
        Integer code = myException.getCode();
        commonResult.setData(msg);
        commonResult.setCode(code);
        commonResult.setMsg(msg);
        return commonResult;

    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult<?> handlerExceptionBindingResult(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuffer stringBuffer = new StringBuffer("");
        for (FieldError fieldError : fieldErrors) {
            stringBuffer.append(fieldError.getField()+fieldError.getDefaultMessage()+"\t");
        }
        CommonResult commonResult = new CommonResult();
        commonResult.setMsg(stringBuffer.toString());
        commonResult.setCode(400);
        return commonResult;
    }
}
